<template>
  <div class="product-detail">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button @click="$router.back()">
        <el-icon><ArrowLeft /></el-icon>返回</el-button>
      </div>
    </div>
    
    <!-- 商品图片轮播 -->
    <el-carousel :interval="4000" arrow="always">
      <el-carousel-item v-for="(image, index) in productImages" :key="index">
        <img :src="image" alt="商品图片" class="product-image">
      </el-carousel-item>
    </el-carousel>
    
    <!-- 商品信息 totalPrice  -->
    <div class="product-info">
      <div class="product-price">
        <span class="price-symbol">¥</span>
        <span class="product-price-value">{{ product.price + currentPriceAdd }}</span>
      </div>
      <div class="product-name">{{ product.name }}</div>
      <div class="product-sold">已售 {{ product.sales }}件</div>
      
      <!-- 规格选择（新增） -->
      <div class="product-spec" @click="showSpecDialog = true">
        <span>规格</span>
        <span class="spec-value">{{ selectedSpec || '请选择' }}</span>
        <el-icon class="select-icon"><ArrowDown  /></el-icon>
      </div>
      
      <!-- 已选（可点击选择数量） -->
      <div class="product-selected" @click="showQuantityDialog = true">
        <span>已选</span>
        <span class="selected-value">{{ selectedInfo }}</span>
        <el-icon class="select-icon"><ArrowDown  /></el-icon>
      </div>
      
      <!-- 送至（可点击选择地址） -->
      <div class="product-delivery" @click="showAddressDialog = true">
        <span>送至</span>
        <span class="delivery-value">{{ selectedAddress }}</span>
        <el-icon class="select-icon"><ArrowDown  /></el-icon>
      </div>
      
      <div class="product-service">
        <span>专业服务</span>
        <span class="service-value">7天无理由·24小时极速退款·商城专属服务</span>
      </div>
      
      <div class="product-evaluation">
        <span v-if="product.evaluation">评价 {{ product.evaluation.count }}</span>
        <span v-if="product.evaluation" class="evaluation-percentage">好评{{ product.evaluation.percentage }}%</span>
        <el-icon v-if="product.evaluation && product.evaluation.count > 2" @click="goToReviewDetail" class="arrow-icon">
          <ArrowRight />
        </el-icon>
      </div>
    </div>
    
    <!-- 用户评价 -->
    <div class="product-comments">
      <div class="comment-section-title">
        <h3>用户评价</h3>
      </div>
      <div v-if="product.comments && product.comments.length > 0" class="comments-container">
        <div v-for="(comment, index) in product.comments.slice(0, 2)" :key="index" class="comment-item">
          <div class="comment-header">
            <el-avatar :size="36" :src="comment.avatar || 'https://picsum.photos/36/36'"></el-avatar>
            <div class="comment-user-info">
              <div class="comment-username">{{ comment.username }}</div>
              <div class="comment-rating">
                <el-rate :value="comment.rating" disabled show-text text-color="#ff9900" />
              </div>
            </div>
            <div class="comment-time">{{ comment.time }}</div>
          </div>
          <div class="comment-content">
            <p>{{ comment.content }}</p>
            <div v-if="comment.images && comment.images.length > 0" class="comment-images">
              <img 
                v-for="(img, idx) in comment.images" 
                :key="idx" 
                :src="img" 
                alt="评价图片" 
                class="comment-image"
              >
            </div>
          </div>
        </div>
        <div v-if="product.comments.length > 2" class="view-all-comments" @click="goToReviewDetail">
          查看全部 {{ product.evaluation.count }} 条评价 <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
      <div v-else class="no-comments">
        暂无评价
      </div>
    </div>
  
    <!-- 商品详情 -->
    <div class="product-details">
      <h3>详情</h3>
      <div class="detail-item" v-for="(detail, index) in productDetails" :key="index">
        <img :src="detail.image" alt="详情图片" class="detail-image">
        <div class="detail-text">
          <h2>{{ detail.title }}</h2>
          <p>{{ detail.description }}</p>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮product.price + currentPriceAdd -->
    <div class="product-actions">
      <span class="product-price">
        <span class="price-symbol">¥</span>
        <span class="product-price-value">{{ totalPrice }}</span>
      </span>
      <el-button type="primary" class="buy-button" @click="buyProduct">立即购买</el-button>
      <el-button type="primary" class="cart-button" @click="addToCart">加入购物车</el-button>
    </div>
    <!--  @click="selectedSpec = spec" -->
 
    
<!-- 规格选择弹窗（修改后） -->
<el-dialog title="选择规格" v-model="showSpecDialog" width="300px">
  <div class="spec-groups">
    <!-- 循环每个规格类型（如颜色、尺寸） -->
    <div v-for="group in specList" :key="group.specId" class="spec-group">
      <div class="spec-group-name">{{ group.specName }}</div> <!-- 显示规格类型名称 -->
      <div class="spec-options">
        <!-- 循环该规格类型下的选项 --> <!-- 点击时传递 specId 和选项 -->
        <div 
          v-for="option in group.options" 
          :key="option"
          class="spec-item"
          :class="{ 'active': selectedSpec === option && selectedSpecId === group.specId }"
          @click="selectSpec(group.specId, option)" 
        >
          {{ option }}
        </div>
      </div>
    </div>
  </div>
  <template #footer>
    <el-button @click="showSpecDialog = false">确定</el-button>
  </template>
</el-dialog>

  

    <!-- 数量选择弹窗（修改后） -->
<el-dialog title="选择数量" v-model="showQuantityDialog" width="300px">
  <div class="quantity-selector">
    <el-button 
      type="text" 
      @click="quantity = Math.max(1, quantity - 1)"
      :disabled="quantity <= 1"
    >
      <el-icon><Minus /></el-icon>
    </el-button>
    <span class="quantity-value">{{ quantity }}</span>
    <el-button 
      type="text" 
      @click="quantity += 1"
      :disabled="quantity >= 99"
    >
      <el-icon><Plus /></el-icon>
    </el-button>
  </div>
  
  <!-- 新增：显示当前数量对应的总价 .toFixed(2)-->
  <div class="quantity-price">
    总价：¥{{ totalPrice }}  <!-- toFixed(2) 保留两位小数 -->
  </div>
  
  <template #footer>
    <el-button @click="showQuantityDialog = false">确定</el-button>
  </template>
</el-dialog>
    
    <!-- 地址选择弹窗 -->
    <el-dialog title="选择收货地址" v-model="showAddressDialog" width="500px">
      <div class="address-list">
        <div 
          v-for="(addr, idx) in addressList" 
          :key="idx"
          class="address-item"
          :class="{ 'active': selectedAddressId === idx }"
          @click="selectedAddressId = idx"
        >
          <div class="address-name">{{ addr.name }} {{ addr.phone }}</div>
          <div class="address-detail">{{ addr.detail }}</div>
        </div>
        <el-button type="primary" class="add-address" @click="addNewAddress">
          <el-icon><Plus /></el-icon> 添加新地址
        </el-button>
      </div>
      <template #footer>
        <el-button @click="showAddressDialog = false">确定</el-button>
      </template>
    </el-dialog>
  
</template>

<script setup>
import { ref, onMounted, computed,watch  } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import CommentList from '../../components/CommentList/index.vue'
import { ArrowLeft, ArrowRight, ArrowDown , Plus, Minus } from '@element-plus/icons-vue'
import { ElRate, ElAvatar, ElDialog, ElButton, ElIcon } from 'element-plus'
import {findAll,findOpt,findAddPriceById} from '@/api/mall.js'

// 路由相关 ArrowDown 
const route = useRoute()
const router = useRouter()
const productId = ref(route.params.id)

// 状态管理
const product = ref({
  price:0,
  name:'',
  sales:''
})
const productImages = ref([])
const productDetails = ref([])
const loading = ref(true)

// 规格选择（新增）
// const specList = ref(['蓝色', '粉红色', '橙色', '紫色', '蔚蓝色', '亮黑色'])

const showSpecDialog = ref(false)

// 存储后端返回的规格数据
const specData = ref([])
// 存储规格id和对应价格增加的映射关系
const optionIdPriceAddMap = ref({})
// 假设选择的specId和optionValue（这里先初始化为示例值，实际使用中应根据用户操作获取）
const selectedSpecId = ref(null)
// const selectedOptionValue = ref('') // '大' 
const selectedSpec = ref(''); // 记录选中的 optionValue
// 存储根据选择查出的optionId
const selectedOptionId = ref(null)
// 选择规格时，同时接收 specId 和 optionValue
const selectSpec = (specId, optionValue) => {
  selectedSpecId.value = specId; // 动态更新 selectedSpecId
  selectedSpec.value = optionValue; // 记录选中的选项值

  // 后续逻辑：根据 specId 和 optionValue 查 optionId 和价格
  const foundOption = specData.value.find(
    item => item.specId === specId && item.optionValue === optionValue
  );
  if (foundOption) {
    selectedOptionId.value = foundOption.optionId;
    findAddPriceById(foundOption.optionId).then(res => {
       console.log('获取到的规格加价:', res.data.priceAdd) // 添加调试输出
      currentPriceAdd.value = res.data.priceAdd;
    });
  } else {
    console.warn('未找到匹配的规格');
  }
};
// 当前选择规格的加价           selectedSpec = spec

const currentPriceAdd = ref(0)

// 数量选择
const quantity = ref(1)
const showQuantityDialog = ref(false)

// 地址选择
const addressList = ref([
  {
    name: '张三',
    phone: '13800138000',
    detail: '河北省石家庄市高新区科技中心B座88层大楼'
  },
  {
    name: '张三',
    phone: '13800138000',
    detail: '河北省石家庄市裕华区科技中心B座99楼'
  }
])
const selectedAddressId = ref(0)
const showAddressDialog = ref(false)

// 计算属性：已选信息
const selectedInfo = computed(() => {
  return `${selectedSpec.value || '未选择规格'} ${quantity.value}件`
})

// 计算属性：选中的地址
const selectedAddress = computed(() => {
  return addressList.value[selectedAddressId.value]?.detail || '请选择地址'
})

// 用于存储从后端获取的商品列表数据
const productsFromBackend = ref([])
// 用于存储模拟数据（以动态id作为键名）
const mockProducts = ref({}) 
// 初始化模拟数据（确保在使用前完成）
//const specList = ref(['蓝色', '粉红色', '橙色', '紫色', '蔚蓝色', '亮黑色'])

 // 调整 specList 结构为：[{specId:1, specName:'颜色', options:['蓝色','红色']}, ...]
const specList = ref([]); // 不再是单纯的选项数组，而是包含 specId 的分组结构

const initOptInfo = () => {
  findOpt(route.params.id).then(res => {
    if (res.code === 200) {
      console.log("后端规格数据：", res.data);
      specData.value = res.data;

      // 按 specId 分组，构建包含 specId 的规格列表
      const specGroups = {};
      res.data.forEach(item => {
        if (!specGroups[item.specId]) {
          // 假设后端有 specName，若没有可自定义（如 '规格1'）
          specGroups[item.specId] = {
            specId: item.specId,
            specName: item.specName || `规格${item.specId}`, // 规格类型名称
            options: [] // 该规格下的选项
          };
        }
        specGroups[item.specId].options.push(item.optionValue);
      });

      // 转换为数组，赋值给 specList
      specList.value = Object.values(specGroups);
    } else {
      alert("请求失败");
    }
  }).catch(err => {
    console.log("请求错误：", err);
  });
};


// const mockProducts = ref({}) 
const initAllInfo =  async () =>{
  try {
    const res = await findAll(); // 等待findAll接口返回
    if (res.code === 200) {
      console.log("后端返回数据：", res.data);
      console.log("后端返回的价格数据：", res.data.map(item => item.price)); // 新增日志，查看价格数据
      productsFromBackend.value = res.data;
      
      // // 循环处理数据（确保接口数据完全返回后再构建mockProducts）
      productsFromBackend.value.forEach(product => {
        const productId = product.id;
        mockProducts.value[productId] = {
          price: product.price,
          name: product.name,
          sales: product.sales,
          images: [product.img]
        };
        console.log('mockProducts----',mockProducts.value)
      }); 
    
      // 数据处理完成后，调用loadProductData
      loadProductData();
    } else {
      alert("请求失败");
    }
  } catch (err) {
    alert("请求错误");
    console.log("请求错误：", err);
  }
}


const isProductDataLoaded = ref(false); // 新增标志变量


import { nextTick } from 'vue'; // 引入nextTick

const loadProductData = async () => {
  console.log('加载商品数据，ID:', productId.value);
  const mockData = mockProducts.value[productId.value]; 
  if (mockData) {
    product.value = mockData;
    productImages.value = mockData.images;
    productDetails.value = mockData.details;
    // 强制等待一个DOM更新周期，确保数据完全同步
    await nextTick();
    isProductDataLoaded.value = true;
    console.log('商品基础价格:', product.value.price);
    // 确保数据同步后再计算总价
    if (product.value.price) {
      totalPrice.value = (product.value.price + currentPriceAdd.value) * quantity.value;
    }
  } else {
    console.error('商品不存在，ID:', productId.value);
  }
  
  loading.value = false;
};
// 新增：计算数量×单价的总价
const totalPrice = ref(0);
const finalPrice = ref(0);
watch(
  () => [quantity.value, product.price, currentPriceAdd.value],
  () => {
    // 改为检查product对象是否完全初始化
    if (!product.value || !product.value.price) {
      console.log("数据未就绪，跳过计算");
      return;
    }
    
    const basePrice = Number(product.value.price)|| 0;
    console.log("基础价格",basePrice)
    const addPrice = Number(currentPriceAdd.value) || 0;
    console.log("加价价格",addPrice)
    const count = Number(quantity.value)||1;
    // if (isNaN(basePrice)) {
    //   console.error("基础价格格式错误:", product.value.price);
    //   return;
    // }
     if (isNaN(basePrice) || isNaN(addPrice)) {
      console.error("价格格式错误:", {
        basePrice: product.value.price,
        addPrice: currentPriceAdd.value
      });
      return;
    }
     finalPrice.value = basePrice + addPrice;
     console.log("finalPrice",finalPrice)
    totalPrice.value = (basePrice + addPrice) * count;
    console.log(`总价计算：(${basePrice} + ${addPrice}) × ${count} = ${totalPrice.value}`);
  },
  { immediate: true }
);



// 跳转到评价详情页
const goToReviewDetail = () => {
  router.push({
    name: 'ReviewDetail',
    params: { productId: productId.value }
  })
}

// 添加新地址
const addNewAddress = () => {
  // 实际项目中会跳转到添加地址页面
  console.log('添加新地址')
  // 这里使用模拟数据
  addressList.value.push({
    name: '新地址',
    phone: '请输入手机号',
    detail: '请输入详细地址'
  })
  selectedAddressId.value = addressList.value.length - 1
}

// 购买相关方法
const buyProduct = () => {
  if (!selectedSpec.value) {
    alert('请选择商品规格')
    return
  }
  
  console.log(`立即购买：${selectedInfo.value}，送至：${selectedAddress.value}`)
  const cartItems = [
    // { productId: '1', spec: 'spec1', quantity: 2, addressId: 'addr1', price: 10 },
    { productId: productId.value, 
      spec: selectedSpec.value, 
      quantity: quantity.value, 
      addressId: selectedAddressId.value, 
      price: finalPrice.value,
     image: productImages.value[0] 
    }
];
const encodedCartItems = encodeURIComponent(JSON.stringify(cartItems));
router.push({
    name: 'Checkout',
    query: { cartItems: encodedCartItems }
},console.log("路由的携带的参数","商品id",productId.value,"规格属性",selectedSpec.value,
  "数量",quantity.value,"价格",totalPrice.value,"地址",selectedAddressId.value)
);}
  // 实际项目中可跳转到结算页面
//   router.push({
//     name: 'Checkout',
//     params: [{
//       productId: productId.value,
//       spec: selectedSpec.value,
//       quantity: quantity.value,
//       addressId: selectedAddressId.value,
//       price: totalPrice.value
//     }]
//   },console.log("路由的携带的参数","商品id",productId.value,"规格属性",selectedSpec.value,
//   "数量",quantity.value,"价格",totalPrice.value,"地址",selectedAddressId.value)
// )
// }

const addToCart = () => {
  if (!selectedSpec.value) {
    alert('请选择商品规格')
    return
  }
  
  console.log(`加入购物车：${selectedInfo.value}，送至：${selectedAddress.value}`)
  // 实际项目中可调用添加购物车接口
  // 这里使用localStorage模拟
  const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]')
  const existingItem = cartItems.find(item => 
    item.productId === productId.value && item.spec === selectedSpec.value
  )
  
  if (existingItem) {
    existingItem.quantity += quantity.value
  } else {
    cartItems.push({
      productId: productId.value,
      name: product.value.name,
      spec: selectedSpec.value,
      price: product.value.price,
      quantity: quantity.value,
      image: productImages.value[0]
    })
  }
  
  localStorage.setItem('cartItems', JSON.stringify(cartItems))
  alert('已加入购物车')
}

// 生命周期钩子：组件挂载后加载数据 //  fetchProducts()
 
onMounted(async () => {
  console.log("传递过来的商品id",route.params.id)
  await initAllInfo();
  initOptInfo()
})
</script>

<style scoped>
.quantity-price {
  margin-top: 20px;
  text-align: center;
  color: #ff4d4f; /* 红色强调价格 */
  font-size: 16px;
}
/* 基础样式 */
.product-detail {
  padding: 15px;
  max-width: 1200px;
  margin: 0 auto;
}

.back-button {
  margin-bottom: 15px;
}

.product-image {
  width: 100%;
  height: auto;
  max-height: 500px;
  object-fit: cover;
}

.product-info {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.product-price {
  font-size: 24px;
  color: #f40;
  margin-bottom: 10px;
}

.price-symbol {
  font-size: 16px;
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-sold {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}

/* 选择项样式 */
.product-spec, .product-selected, .product-delivery {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.product-spec span:first-child, 
.product-selected span:first-child, 
.product-delivery span:first-child {
  width: 60px;
  color: #999;
}

.spec-value, .selected-value, .delivery-value {
  flex: 1;
  margin-left: 10px;
}

.select-icon {
  color: #999;
}

/* 服务信息样式 */
.product-service {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.product-service span:first-child {
  width: 60px;
  color: #999;
}

.service-value {
  flex: 1;
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

/* 评价样式 */
.product-evaluation {
  display: flex;
  align-items: center;
  padding: 10px 0;
  color: #666;
}

.evaluation-percentage {
  margin-left: 10px;
  color: #f40;
}

.arrow-icon {
  margin-left: 5px;
  cursor: pointer;
}

/* 评价列表样式 */
.comment-section-title {
  margin: 20px 0 10px;
}

.comments-container {
  margin-bottom: 20px;
}

.comment-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.comment-user-info {
  flex: 1;
  margin-left: 10px;
}

.comment-username {
  font-weight: bold;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin-bottom: 10px;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.comment-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.view-all-comments {
  text-align: center;
  color: #409eff;
  cursor: pointer;
  padding: 10px 0;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

/* 详情样式 */
.product-details {
  margin: 20px 0;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-image {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
}

.detail-text h2 {
  font-size: 18px;
  margin-bottom: 5px;
}

.detail-text p {
  color: #666;
}

/* 操作按钮样式 */
.product-actions {
  position: fixed;
  bottom: 0;
  left: 204px;
  right: 0;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: white;
  border-top: 1px solid #eee;
  z-index: 100;
}

.product-actions .product-price {
  margin-right: 15px;
}

.buy-button{
   background-color: red; /* 设置背景色为红色 */
  color: white; /* 设置文字颜色为白色 */
  border: none; /* 去掉边框 */
  border-radius: 20px; /* 设置圆角，数值越大角越圆，这里让按钮呈近似椭圆 */
  padding: 10px 20px; /* 设置内边距，调整按钮内文字与边框的距离 */
  font-size: 18px; /* 设置文字大小 */
  cursor: pointer; /* 鼠标悬停时显示指针样式，提示可点击 */
  /* flex: 1;
  margin: 0 5px; */
  margin-left: 200px;

}
.cart-button {
   background-color: rgb(54, 152, 198); /* 设置背景色为红色 */
  color: white; /* 设置文字颜色为白色 */
  border: none; /* 去掉边框 */
  border-radius: 20px; /* 设置圆角，数值越大角越圆，这里让按钮呈近似椭圆 */
  padding: 10px 20px; /* 设置内边距，调整按钮内文字与边框的距离 */
  font-size: 18px; /* 设置文字大小 */
  cursor: pointer; /* 鼠标悬停时显示指针样式，提示可点击 */
  /* flex: 1;
  margin: 0 5px; */
  margin-left: 220px;
}

/* 弹窗样式 */
.quantity-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.quantity-value {
  width: 60px;
  text-align: center;
  font-size: 18px;
}

.address-list {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.address-item {
  padding: 15px;
  border: 1px solid #eee;
  margin-bottom: 10px;
  cursor: pointer;
}

.address-item.active {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.address-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.add-address {
  width: 100%;
}

/* 规格选择样式 */
.spec-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px 0;
}

.spec-item {
  padding: 10px 15px;
  border: 1px solid #eee;
  margin: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
}

.spec-item.active {
  border-color: #409eff;
  background-color: #f5f7fa;
}
</style>